package glen.security.service;

import glen.util.MyBatisConnectionFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Set;

/**
 * Created by rachatanawee on 4/9/2014.
 */
public class CustomSecurityRealm extends JdbcRealm {
    static protected SqlSessionFactory sf;

    protected String authenticationQuery = DEFAULT_AUTHENTICATION_QUERY;

    protected String userRolesQuery = DEFAULT_USER_ROLES_QUERY;

    protected boolean permissionsLookupEnabled = false;

    private static final Logger log = LoggerFactory.getLogger(CustomSecurityRealm.class);


    public CustomSecurityRealm() {
        super();
        this.sf = MyBatisConnectionFactory.getSqlSessionFactory();
    }


    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        // Null username is invalid
        if (username == null) {
            throw new AccountException("Null usernames are not allowed by this realm.");
        }


        AuthenticationInfo info;
        try (SqlSession session = sf.openSession()) {


            String password = session.selectOne("JdbcRealm.authenticationQuery", username);

            if (password == null) {
                throw new UnknownAccountException("No account found for user [" + username + "]");
            }

            info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
            //info = new MySaltedAuthentificationInfo(username, password, "drowssaps");

        }

        return info;
    }

    @Override
    protected Set<String> getPermissions(Connection conn, String username, Collection<String> roleNames) throws SQLException {

        Set permissions;
        try (SqlSession session = sf.openSession()) {
            permissions = (Set) session.selectList("userPermissionQuery", username);

        }
        return permissions;
    }

    @Override
    protected Set getRoleNamesForUser(Connection conn, String username) throws SQLException {

        Set roleNames;
        try (SqlSession session = sf.openSession()) {
            roleNames = (Set) session.selectList("userRolesQuery", username);

        }

        return roleNames;
    }
}
